package com.devicemantra.coordinate.interfaces.call;

import java.io.IOException;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sun.misc.Perf;

import com.devicemantra.coordinate.ds.tests.*;
import com.devicemantra.coordinate.util.CLogger;

public class CallTask extends HttpServlet 
{
	private static String lBaseUrl = "http://www.gaetaskapi.appspot.com/";
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
	throws IOException 
	{
		doGet(req,resp);
	}
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
	throws IOException {
	
	CLogger.log("Call task started");
	System.out.println("Call task started");
	String lMobileNumber = req.getParameter("mobile_number");
	String lCallMesgId = req.getParameter("call_responder_id");
	System.out.println("Mob " + lMobileNumber + " lCallMesgId" + lCallMesgId);
	
	System.out.println("Fetching message for Message id");
	boolean lDoesExist = true;
	PersistenceManager lPMF = PMF.get().getPersistenceManager();
	CCallMessage lCMessage = null;
	try
	{
		lCMessage = lPMF.getObjectById(CCallMessage.class,lCallMesgId);
	} catch(JDOObjectNotFoundException e)
	{
		lDoesExist = false;
	}
	
	if(false == lDoesExist)
	{
		System.out.println("FATAL ERROR: The message id does not exist");
		return;
	}
	System.out.println("The message retreived is " + lCMessage.getMessage());
	String lUrl = lBaseUrl + "getVoiceMessage?" + "id=" + lCallMesgId;
	System.out.println("Url to call for twilio is " + lUrl);
	CMakeCall.makeCallExample(lMobileNumber, lUrl);
	
	}

}
